﻿using Kairos.Models;
using System.Collections.Generic;
using System.Configuration;
using System.Data.Entity;
using System.Data.SqlClient;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;

namespace Kairos.Migrations
{
    public class myCreateDatabaseIfNotExists : CreateDatabaseIfNotExists<myContext>
    {
        [SuppressMessage("Microsoft.Security", "CA2100:Review SQL queries for security vulnerabilities")]
        public override void InitializeDatabase(myContext context)
        {
            base.InitializeDatabase(context);

            IEnumerable<string> commandStrings;

            using (var reader = new StreamReader(Utilities.ExtractFromAssembly<Stream>("fulltext.sql")))
            {
                string sql = reader.ReadToEnd();

                commandStrings = Regex.Split(sql, @"^\s*GO\s*$", RegexOptions.Multiline | RegexOptions.IgnoreCase)
                    .Where(c => !string.IsNullOrWhiteSpace(c));
            }

            string connectionString = ConfigurationManager.ConnectionStrings[Utilities.AssemblyName].ConnectionString;

            using (var cn = new SqlConnection(connectionString))
            {
                cn.Open();
                foreach (var commandString in commandStrings)
                    using (var cmd = new SqlCommand(commandString, cn))
                        cmd.ExecuteNonQuery();
            }
        }
    }
}